/*
 * Copyright 2019-2020 by Nedim Sabic Sabic
 * https://www.fibratus.io
 * All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package app

import (
	"github.com/rabbitstack/fibratus/internal/bootstrap"
	"github.com/rabbitstack/fibratus/pkg/config"
	"github.com/rabbitstack/fibratus/pkg/util/multierror"
	ver "github.com/rabbitstack/fibratus/pkg/util/version"
	"github.com/spf13/cobra"
)

var runCmd = &cobra.Command{
	Use:     "run [filter]",
	Short:   "Bootstrap fibratus or a filament",
	Aliases: []string{"start"},
	RunE:    run,
	Example: `
	# Run without the filter
	fibratus run

	# Run with the filter that drops all but events produced by the svchost.exe process
	fibratus run ps.name = 'svchost.exe'

	# Run with the filter that traps all events that were generated by process that contains the 'svc' string and specific security identifiers
	fibratus run ps.name contains 'svc' and ps.sid in ('S-1-5-18', 'S-1-5-19')

	# Run the top_keys filament
	fibratus run -f top_keys
	`,
}

var (
	// the run command config
	cfg = config.NewWithOpts(config.WithRun())
)

func init() {
	// initialize flags
	cfg.MustViperize(runCmd)
}

func run(cmd *cobra.Command, args []string) error {
	ver.Set(version)
	app, err := bootstrap.NewApp(cfg, bootstrap.WithSignals(), bootstrap.WithDebugPrivilege())
	if err != nil {
		return err
	}
	if err := app.Run(args); err != nil {
		return multierror.Wrap(err, app.Shutdown())
	}
	app.Wait()
	return app.Shutdown()
}
